package eai.tp1;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import eai.tp1.core.SSEngine;
import eai.tp1.core.datamodel.DataManager;
import eai.tp1.core.datamodel.DigitalCamera;
import eai.tp1.core.source.CCUExtractor;
import eai.tp1.core.source.DPreviewExtractor;
import eai.tp1.core.source.Extractor;
import eai.tp1.core.source.IWebPageSource;
import eai.tp1.utils.User;

/**
 * This class is the main of the application. It reads the brand and the web pag
 * source from the command line and send it to the scrap screening engine.
 * 
 * @author Joel
 * 
 */
public class Main {

	public static void main(String args[]) {
		Main console = new Main();
		console.initExtractors();
		console.start();
	}

	public void start() {
		while (true) {
			System.out.println("Usage: '<brand>'.");
			System.out.print(prompt);
			String line = User.readString().trim();
			if (line.isEmpty())
				continue;
			if (line.equalsIgnoreCase("quit")) {
				break;
			}
			Extractor extractor;
			IWebPageSource webSource;
			String[] parameters = line.split("\\s+");
			if (parameters.length == 1) {
				extractor = parse(defaultSrc);
				webSource = extractor.factoryMethod();
				try {
					List<DigitalCamera> cameras = this.scraping.extract(
							webSource, parameters[0]);
					// dataManager.print(cameras);
					dataManager.write(cameras,parameters[0], webSource.getRootLink());
					dataManager.createXML(parameters[0]+".xml");
				} catch (IOException e) {
					System.out.println("Error! The brand doesn't exist.");
				}
			} else if(parameters.length == 2) {
				extractor = parse(parameters[0]);				
				if(extractor!=null) {
					webSource = extractor.factoryMethod();
					try {
						List<DigitalCamera> cameras = this.scraping.extract(
								webSource, parameters[1]);
						dataManager.write(cameras,parameters[1], webSource.getRootLink());
						dataManager.createXML(parameters[1]+".xml");
					} catch (IOException e) {
						System.out.println("Error! The brand doesn't exist.");
					}
				}
				else System.out.println("Command error! Usage: '<dpreview/ccu> <brand>'.");
			} else
				System.out.println("Command error! Usage: '<brand>'.");
		}
	}

	protected void initExtractors() {
		extractors = new HashMap<String, Extractor>();
		extractors.put("dpreview", new DPreviewExtractor());
		extractors.put("ccu", new CCUExtractor());
	}

	protected Extractor parse(String commandName) {
		if (extractors.containsKey(commandName))
			return extractors.get(commandName);
		else
			return null;
	}

	private String prompt = "\n$ ";
	private String defaultSrc = "dpreview";
	protected Map<String, Extractor> extractors;
	protected SSEngine scraping = new SSEngine();
	protected DataManager dataManager = new DataManager();	
}
